package com.vq.controller;

import com.vq.common.R;
import com.vq.common.Message;
import com.vq.common.UserLibrary;
import com.vq.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Slf4j
@Controller
@RequestMapping("/Chat")
public class ChatController {
    @Autowired
    HttpSession session;

    /**
     * 发送消息
     * @return
     */
    @PostMapping
    @ResponseBody
    public R sending(@RequestBody Message message) {
        User user = (User) session.getAttribute("myUser");
        message.setSenderAcc(user.getAccount());
        log.info("发送消息："+message);
        //添加消息
        if(UserLibrary.sending(message)){
            return new R(1, message);
        } else {
            return new R(0);
        }
    }

    /**
     * 接收消息
     * @return
     */
    @GetMapping("/{account}")
    @ResponseBody
    public R<Message> accept(@PathVariable String account) {
        User user = (User) session.getAttribute("myUser");
        if (user==null) return null;
        //查询消息
        Message message = UserLibrary.accept(account, user.getAccount());
        //拒绝响应
        if (message==null) {
            return null;
        } else {
            log.info("接收消息："+message);
            return new R<>(1, message);
        }
    }
}
